package com.baosight.risk.service.ridc.impl;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtdc.XtdcAttachService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.fltd.FlaaNodeAuthoMapper;
import com.baosight.risk.mapper.fltd.FltdTaskMapper;
import com.baosight.risk.mapper.ridc.*;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.fltd.vo.NodeTransitionVO;
import com.baosight.risk.service.ridc.entity.*;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("ridcRiskSubServiceImpl")
public class RidcRiskSubServiceImpl extends BaseServiceImpl<RidcRisk> implements UpdateHandler, AfterHandler {
    @Autowired
    private RiimRiskImportMapper riimRiskImportMapper;

    @Autowired
    private RidcRiskMapper ridcRiskMapper;

    @Autowired
    private RidcRiskDescMapper ridcRiskDescMapper;

    @Autowired
    private RidcRiskEvaluateMapper ridcRiskEvaluateMapper;

    @Autowired
    private RidcRiskEvaluateResultMapper ridcRiskEvaluateResultMapper;

    @Autowired
    private RidcRiskAdvanceMapper ridcRiskAdvanceMapper;

    @Autowired
    private XtzyUserMapper xtzyUserMapper;

    @Autowired
    private FltdTaskMapper fltdTaskMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private FlaaNodeAuthoMapper flaaNodeAuthoMapper;
    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;
    @Autowired
    private XtdcAttachService xtdcAttachService;


    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean doAfter(Map<String, Object> params) {
        try{
            RiimRiskImport riskImport=new RiimRiskImport();
            riskImport.setId(params.get("taskGuid").toString());
            //重点风险id查询出重点风险信息
            RiimRiskImport riimImport1 = riimRiskImportMapper.selectById(riskImport);
            //根据parentId获取上级点位的重点风险
            RiimRiskImport parentRiskImport=new RiimRiskImport();
            parentRiskImport.setId(riimImport1.getParentId());
            RiimRiskImport parentRiskList =riimRiskImportMapper.selectById(parentRiskImport);
            //根据上级单位的风险序号和年度加管理单位查询出对应的上级单位风险档案
            RidcRisk paramRidcRisk=new RidcRisk();
            paramRidcRisk.setRiskNo(parentRiskList.getRiskNo());
            paramRidcRisk.setAcctYear(parentRiskList.getAcctYear());
            paramRidcRisk.setManageCompCode(parentRiskList.getManageCompCode());
            List<RidcRisk> parentArchivesList=ridcRiskMapper.selectList(paramRidcRisk);
            for (RidcRisk parentRiskItem :parentArchivesList){
                if("B01".equals(parentRiskItem.getStatus())){
                    //修改风险档案（T_RIDC_RISK）的维护日期（LAST_UPDATE_DATE）
                    parentRiskItem.setLastUpdateDate(new Date());
                    ridcRiskMapper.updateByPrimaryKey(parentRiskItem);
                    RidcRisk subEntity=new RidcRisk();
                    subEntity.setId(params.get("bizGuid").toString());
                    RidcRisk subArchives =ridcRiskMapper.selectOne(subEntity);
                    this.copyArchivesData(parentRiskItem,subArchives);
                    this.submit(parentRiskItem,parentRiskList);
                }else{
                    throw new Exception("宝钢股份重点风险监控报告的工作流节点不符合条件，请先提交宝钢股份相同重点风险监控报告的工作流！");
                }
            }
        }catch (Exception e){
            log.error("扭转流程异常："+e.getMessage());
            return false;
        }

        return true;
    }

    @Override
    public boolean updateStatus(Map<String, Object> params) {
        return false;
    }

    public void copyArchivesData(RidcRisk parentEntity,RidcRisk subEntity){
        this.deleteArchivesData(parentEntity.getId());
        //复制风险描述（T_RIDC_RISK_DESC）
        RidcRiskDesc riskDesc=new RidcRiskDesc();
        riskDesc.setDocRiskId(subEntity.getId());
        List<RidcRiskDesc> riskDescList=ridcRiskDescMapper.select(riskDesc);
        for (RidcRiskDesc itemDesc:riskDescList) {
            RidcRiskDesc riskDescEntity=new RidcRiskDesc();
            BeanUtils.copyBeanProp(riskDescEntity,itemDesc);
            BeanUtils.initBean(riskDescEntity);
            riskDescEntity.setDocRiskId(parentEntity.getId());
            ridcRiskDescMapper.insert(riskDescEntity);
        }
        //复制风险评估T_RIDC_RISK_EVALUATE
        RidcRiskEvaluate riskEvaluate=new RidcRiskEvaluate();
        riskEvaluate.setDocRiskId(subEntity.getId());
        List<RidcRiskEvaluate> evaluateList=ridcRiskEvaluateMapper.select(riskEvaluate);
        for (RidcRiskEvaluate evaluateItem:evaluateList) {
            RidcRiskEvaluate  riskEvaluateInsert=new RidcRiskEvaluate();
            BeanUtils.copyBeanProp(riskEvaluateInsert,evaluateItem);
            BeanUtils.initBean(riskEvaluateInsert);
            riskEvaluateInsert.setDocRiskId(parentEntity.getId());
            ridcRiskEvaluateMapper.insert(riskEvaluateInsert);
        }
        //复制风险评估结论T_RIDC_RISK_EVALUATE_RESULT
        RidcRiskEvaluateResult riskEvaluateResult=new RidcRiskEvaluateResult();
        riskEvaluateResult.setDocRiskId(subEntity.getId());
        List<RidcRiskEvaluateResult> evaluateResultList=ridcRiskEvaluateResultMapper.select(riskEvaluateResult);
        for (RidcRiskEvaluateResult evaluateResultItem:evaluateResultList) {
            RidcRiskEvaluateResult  evaluateResult=new RidcRiskEvaluateResult();
            BeanUtils.copyBeanProp(evaluateResult,evaluateResultItem);
            BeanUtils.initBean(evaluateResult);
            evaluateResult.setDocRiskId(parentEntity.getId());
            ridcRiskEvaluateResultMapper.insert(evaluateResult);
        }
        //复制监督与改进（T_RIDC_RISK_ADVANCE）
        RidcRiskAdvance riskAdvance=new RidcRiskAdvance();
        riskAdvance.setDocRiskId(subEntity.getId());
        List<RidcRiskAdvance> riskAdvanceList=ridcRiskAdvanceMapper.select(riskAdvance);
        for (RidcRiskAdvance advanceItem:riskAdvanceList) {
            RidcRiskAdvance  riskAdvanceInsert=new RidcRiskAdvance();
            BeanUtils.copyBeanProp(riskAdvanceInsert,advanceItem);
            BeanUtils.initBean(riskAdvanceInsert);
            riskAdvanceInsert.setDocRiskId(parentEntity.getId());
            ridcRiskAdvanceMapper.insert(riskAdvanceInsert);
        }
    }

    public void deleteArchivesData(String docRiskId){
        ridcRiskDescMapper.deleteRidcRiskDescBydocRiskId(docRiskId);
        ridcRiskEvaluateMapper.deleteRidcRiskEvaluateBydocRidcRiskId(docRiskId);
        ridcRiskEvaluateResultMapper.deleteRidcRiskEvaluateResultBydocRidcRiskId(docRiskId);
        ridcRiskAdvanceMapper.deleteRidcRiskAdvanceBydocRiskId(docRiskId);
    }

    private void submit(RidcRisk parentRiskItem, RiimRiskImport parentRiskImport){
        if(StringUtils.isNotEmpty(parentRiskImport.getDutyUserCode())){
            XtzyUser xtzyUser = xtzyUserMapper.selectByName(parentRiskImport.getDutyUserCode());
            FltdTaskVO paramTask=new FltdTaskVO();
            paramTask.setFlowNo("fengxiandangan");
            paramTask.setBizGuid(parentRiskItem.getId());
            paramTask.setNodeCode(parentRiskItem.getStatus());
            paramTask.setStatus("open");
            List<FltdTask> taskList = fltdTaskMapper.selectTaskList(paramTask);
            if(taskList.size()>0){
                FltdTaskVO taskVoParam=new FltdTaskVO();
                BeanUtils.copyBeanProp(taskVoParam, taskList.get(0));
                try {
                    FltdTask updateTask=new FltdTask();
                    updateTask.setTodoGuid(taskVoParam.getTodoGuid());
                    //走绿色通道
                    updateTask.setGreenFlag("G");
                    fltdTaskMapper.updateByPrimaryKeySelective(updateTask);
                    taskVoParam.setGreenFlag("G");

                    //获取下一节点审批人
                    Map<String, Object> resultMap = flaaNodeAuthoService.getNextUser(taskVoParam, xtzyUser);

                    if(resultMap.get("isEnd")!=null && "1".equals(resultMap.get("isEnd").toString())){
                        //查询指定节点的下一个节点及转移路线
                        String processDefId = fltdProcessService.getProcessDefId(taskVoParam.getProcGuid());
                        NodeTransitionVO nextTransition = flaaNodeAuthoMapper.nextOneNodeTransition(processDefId, "submit-G-1");
                        taskVoParam.setSubmitButton(nextTransition);

                        fltdProcessService.doSubmit(xtzyUser,taskVoParam);
                    }

                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }
}
